package wuaipojie

import (
	"cmp"
	"gitee.com/kaylee595/gkaylee/kerr"
	"golang.org/x/net/html"
	"io"
	"strings"

	"github.com/imroc/req/v3"
)

type Client struct {
	httpClient *req.Client
}

type Options func(*Client)

func WithHttpClient(httpClient *req.Client) Options {
	return func(c *Client) {
		c.httpClient = cmp.Or(httpClient, req.DefaultClient())
	}
}

func NewClient(opts ...Options) *Client {
	client := &Client{
		httpClient: req.DefaultClient(),
	}
	for _, opt := range opts {
		opt(client)
	}
	return client
}

func htmlString(r string) (string, error) {
	dom, err := html.Parse(strings.NewReader(r))
	if err != nil {
		return r, kerr.WrapTraceStack(err)
	}
	var render func(w io.Writer, n *html.Node)
	render = func(w io.Writer, n *html.Node) {
		if n.Type == html.TextNode {
			w.Write([]byte(n.Data))
		}
		if n.Type == html.ElementNode && n.Data == "script" {
			return
		}
		for node := range n.ChildNodes() {
			render(w, node)
		}
	}
	ret := &strings.Builder{}
	render(ret, dom)
	return ret.String(), nil
}
